package com.ruoyi.web.controller.fx;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.dto.FxGoodPurchaseDto;
import com.ruoyi.system.domain.dto.FxOrderDto;
import com.ruoyi.system.domain.dto.GoodDto;
import com.ruoyi.system.domain.dto.TotalRequest;
import com.ruoyi.system.domain.fx.FxOrder;
import com.ruoyi.system.domain.fx.FxStore;
import com.ruoyi.system.domain.vo.FxOrderVo;
import com.ruoyi.system.service.fx.IFxAppointmentService;
import com.ruoyi.system.service.fx.IFxOrderService;
import com.ruoyi.system.service.fx.IFxStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单Controller
 *
 * @author ruoyi
 * @date 2024-07-23
 */
@RestController
@RequestMapping("/fx/order")
public class FxOrderController extends BaseController {
    @Autowired
    private IFxOrderService fxOrderService;

    @Autowired
    private IFxStoreService iFxStoreService;

    @Autowired
    private IFxAppointmentService fxAppointmentService;

    /**
     * 查询订单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(FxOrder fxOrder) {
        Long userId =  SecurityUtils.getUserId();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<Long> roles = SecurityUtils.getLoginUser().getUser().getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList());
        fxOrder.setUserId(userId);
        if (roles.contains(1L) || roles.contains(6L)) {
            fxOrder.setUserId(null);
            fxOrder.setUserRole(4L);
        }
        List<FxOrderVo> list = fxOrderService.selectOrderList(fxOrder);
        return getDataTable(list);
    }

    /**
     * 小程序列表
     * @param fxOrder
     * @return
     */
    @GetMapping("/listApp")
    public TableDataInfo listApp(FxOrder fxOrder) {
        Long userId =  SecurityUtils.getUserId();
        List<Long> roles = SecurityUtils.getLoginUser().getUser().getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList());
        fxOrder.setUserId(userId);
        if (roles.contains(1L) || roles.contains(6L)) {
            fxOrder.setUserId(null);
        }
//        startPage();
        List<FxOrderVo> list = fxOrderService.selectOrderList(fxOrder);
//        List<FxOrderVo> list = fxOrderService.selectFxOrderList(fxOrder);
        for (FxOrderVo order : list) {
            FxStore fxStore= iFxStoreService.selectFxStoreById(order.getStoreId());
            order.setDelivery(fxStore.getStoreName());
            order.setDeliveryPhone(fxStore.getPhoneNumber());
        }
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FxOrder fxOrder) {
        List<FxOrderVo> list = fxOrderService.selectFxOrderList(fxOrder);
        ExcelUtil<FxOrderVo> util = new ExcelUtil<FxOrderVo>(FxOrderVo.class);
        util.exportExcel(response, list, "订单数据");
    }
     // 测试提交
    /**
     * 获取订单详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(fxOrderService.selectFxOrderByOrderId(id));
    }

    /**
     * 获取门店总销售额
     *
     * @param fxOrder
     * @return
     */
    @GetMapping("/getTotalMoney")
    public AjaxResult getTotalMoney(FxOrder fxOrder) {
        List<Long> roles = getLoginUser().getUser().getRoles()
                .stream().map(SysRole::getRoleId).collect(Collectors.toList());
        if (roles.contains(1L) || roles.contains(6L)) {
            return success();
        }
        return success(fxOrderService.getTotalMoney(fxOrder));
    }

    /**
     * 请求支付 （小程序下单）
     * @param fxOrderDto
     * @return
     */
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FxOrderDto fxOrderDto) {
//        return toAjax(fxOrderService.insertFxOrder(fxOrderDto));
        return success(fxOrderService.wxPayOrder(fxOrderDto));
    }

    /**
     * 添加订单 （小程序下单）
     * @param fxOrderDto
     * @return
     */
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping("/createOrder")
    public AjaxResult createOrder(@RequestBody FxOrderDto fxOrderDto) {
        fxOrderService.createOrder(fxOrderDto);
        return success();
    }


    /**
     * 支付回调
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/payNotify")
    @Log(title = "支付回调", businessType = BusinessType.INSERT)
    public AjaxResult payNotify(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = fxOrderService.payNotify(request, response);
        return success(map);
    }



    /**
     * 退单
     * @param fxOrder
     * @return
     */
    @PutMapping("/chargebackOrder")
    public AjaxResult chargebackOrder(@RequestBody FxOrder fxOrder){
        Map<String, Object> result = fxOrderService.chargebackOrder(fxOrder);
        return success(result);
    }

    /**
     * 商品采购下单
     *
     * @return
     */
    @Log(title = "采购", businessType = BusinessType.INSERT)
    @PostMapping("/addPurchase")
    public AjaxResult addPurchase(@RequestBody FxGoodPurchaseDto fxGoodPurchaseDto) {
        return toAjax(fxOrderService.insertPurchase(fxGoodPurchaseDto));
    }

    /**
     * 店铺补货
     * @param fxGoodPurchaseDto
     * @return
     */
    @Log(title = "店铺补货", businessType = BusinessType.INSERT)
    @PostMapping("/replenish")
    public AjaxResult replenish(@RequestBody FxGoodPurchaseDto fxGoodPurchaseDto){
        return toAjax(fxOrderService.insertReplenish(fxGoodPurchaseDto));
    }

    /**
     * 修改订单
     */
    @Log(title = "修改订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FxOrder fxOrder) {
        return toAjax(fxOrderService.updateFxOrder(fxOrder));
    }

    /**
     * 删除订单
     */
    @Log(title = "删除订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(fxOrderService.updateDelFlag(ids));
    }

    /**
     * 扫码出库
     * @return
     */
    @PostMapping("/outBound")
    public AjaxResult outBound(@RequestBody GoodDto goodDto){
        List<GoodDto> goodDtoList = goodDto.getGoodDtoList();
        String id = fxOrderService.outBound(goodDtoList);
        if (StringUtils.isEmpty(id)){
            return error("订单创建失败");
        }
        return success(fxOrderService.selectFxOrderByOrderId(id));
    }

    /**
     * 查询当天的订单数量
     * @return
     */
    @GetMapping("/orderStatistics")
    public AjaxResult orderStatistics(){
        TotalRequest list = fxOrderService.orderStatistics();
        return success(list);
    }

    /**
     * 查询支付的订单
     * @return
     */
    @GetMapping("/orderList")
    public AjaxResult orderList(FxOrder fxOrder,String startTime,String endTime){
        Long userId =  SecurityUtils.getUserId();
        List<Long> roles = SecurityUtils.getLoginUser().getUser().getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList());
        fxOrder.setUserId(userId);
        if (roles.contains(1L) || roles.contains(6L)) {
            fxOrder.setUserId(null);
        }
        return success(fxOrderService.orderList(fxOrder,startTime,endTime));
    }


}
